﻿/********
* Copyright © 深圳市新元素医疗技术开发有限公司 . All rights reserved.
* 
*  Description:
*  Create By Kain at 5/11/2011 4:29:24 PM
*  
*
*  Revision History:
*  Date                  Who                 What
*  
* 
********/

#region namespace

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Objects;
using System.Data.Common;

#endregion

namespace Cherry.Agile.Data.Repository.Extention
{
    /// <summary>
    /// 结果集
    /// </summary>
    public class DataResult:IDisposable
    {
        DbDataReader _reader;
        ObjectContext _context;
        Action _callBack;
        internal DataResult(ObjectContext context, DbDataReader reader,Action callBack)
        {
            _reader = reader;
            _context = context;
            _callBack = callBack;
        }

        bool _ended;
        /// <summary>
        /// 获取一个结果集
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <returns>结果集</returns>
        /// <example>
        /// <code><![CDATA[
        /// using (var result = ObjectContext.ExcuteStoreFunction(sp,p ))
        /// {
        /// 
        ///     var customers = result.Result<Customer>((d) =>
        ///          new Customer()
        ///             {
        ///                 CustomerID = d.GetValue<string>("CustomerID")
        ///             }
        /// 
        ///         ).ToList();
        ///     var orders = result.Result<Order>((d) =>
        ///          new Order()
        ///             {
        ///                 OrderId = d.GetValue<int>("OrderId"),
        ///                 OrderDate = d.GetValue<int>("OrderDate")
        ///             }
        /// 
        ///         ).ToList();
        /// }
        /// ]]>
        /// </code>
        /// </example>
        public IEnumerable<T> Result<T>(Func<IDataRecord,T> process)
        {
            if (_ended)
                yield break;
            while (_reader.Read())
            {
                yield return process(_reader);
            }
            _ended = !_reader.NextResult();
            
        }

        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            if (_reader != null)
            {
                _reader.Close();
                _reader.Dispose();
            }

            if (_context != null)
                _context.Connection.Close();
            _callBack();
        }
    }
}
